package cn.fjc920.siaa.fragments

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.AccessibilityDelegate
import android.view.ViewGroup
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.AccessibilityDelegateCompat
import androidx.core.view.ViewCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activitys.HomePageActivity
import cn.fjc920.siaa.adapters.HoursAdapter
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import cn.fjc920.siaa.itembean.Hours
import kotlinx.android.synthetic.main.home_all_fragment.view.*
import kotlinx.android.synthetic.main.home_today_fragment.*
import kotlinx.android.synthetic.main.home_today_fragment.view.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException
import kotlin.properties.Delegates

/**
 *      描述：今日工时界面
 *      时间：2022-12-06
 *      作者：fanjiancai
 */

class HomeTodayFragment : Fragment() {

    private var isHide by Delegates.notNull<Boolean>()
    private lateinit var rfr: SwipeRefreshLayout
    private lateinit var noData: LinearLayout
    private lateinit var todayRecyclerView: RecyclerView
    private lateinit var homePageActivity: HomePageActivity
    private var adapter: HoursAdapter? = null
    private lateinit var nextUrl: String
    private val url = "${OkhttpUtils.url}item/create"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val activity = activity as HomePageActivity
        val view = inflater.inflate(R.layout.home_today_fragment, container, false)
        init(view,activity)
        return view
    }

    private fun init(view: View,activity: HomePageActivity) {

        activity.getSharedPreferences("cn.fjc920.siaa_preferences",Context.MODE_PRIVATE).apply {
            isHide = getBoolean("hide_user",true)
        }

        rfr = view.today_refresh
        noData = view.noData
        todayRecyclerView = view.today_recyclerView

        homePageActivity = activity as HomePageActivity
        initRefresh(view)
        initList(url, false, isRefresh = false)
    }

    private fun initRefresh(view: View) {

        view.today_refresh.setColorSchemeResources(R.color.purple_500)
        view.today_refresh.setOnRefreshListener {
            initList(url, true, isRefresh = true)
        }
    }

    fun refresh() {
        initList(url, true, isRefresh = true)
    }

    private fun initList(url: String, clearAdapterData: Boolean, isRefresh: Boolean) {

        val hoursList = ArrayList<Hours>()

        OkhttpUtils.getAsync(url, object : OkhttpUtils.DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {
                if (rfr.isRefreshing) {
                    rfr.isRefreshing = false
                    rfr.announceForAccessibility("刷新失败，请检查网络！")
                }
            }

            override fun requestSuccess(result: String?) {

                var doc = Jsoup.parse(result)

                //获取_csrf
                val inputs = doc.getElementById("formCreateItem")!!.select("input[type=hidden]")
                val input = inputs[0]
                var _csrf = input.attr("value")

                val elements = doc.select("tbody tr")
                for (element in elements) {

                    //获取用户
                    val user = element.child(0).text()
                    //获取部门
                    val door = element.child(1).text()
                    //获取日期
                    val date = element.child(2).text()
                    //获取项目
                    val project = element.child(3).text()
                    //获取类型
                    val type = element.child(4).text()
                    //获取时长
                    val time = element.child(5).text()
                    //获取备注
                    val remarks = element.child(6).text()

                    //获取编辑链接
                    val editUrl = element.child(7).child(0).attr("href").substring(1)

                    //获取工时id
                    val hoursId = editUrl.substring(editUrl.indexOf("=") + 1)

                    //获取删除Url
                    val deleteUrl = "${OkhttpUtils.url}item/delete"

                    hoursList.add(
                        Hours(
                            user, door, date, project, type,
                            time, remarks, "${OkhttpUtils.url}${editUrl}", deleteUrl, _csrf, hoursId
                        )
                    )
                }

                if (hoursList.isNotEmpty()) {
                    todayRecyclerView.visibility = View.VISIBLE
                    noData.visibility = View.GONE
                    if (adapter == null) {
                        initAdapter(hoursList)
                    } else {
                        if (clearAdapterData) {
                            adapter!!.clearData()
                        }
                        adapter!!.loadMore(hoursList, isRefresh)
                    }
                    if (rfr.isRefreshing) {
                        rfr.isRefreshing = false
                        rfr.announceForAccessibility("刷新成功!")
                    }
                } else {
                    todayRecyclerView.visibility = View.GONE
                    noData.visibility = View.VISIBLE
                    if (rfr.isRefreshing) {
                        rfr.isRefreshing = false
                        rfr.announceForAccessibility("刷新成功，今日未提交工时！")
                    }
                }
            }
        })
    }

    private fun initAdapter(hoursList: ArrayList<Hours>) {

        val layoutManager = LinearLayoutManager(homePageActivity)
        todayRecyclerView.layoutManager = layoutManager

        adapter = HoursAdapter(hoursList,isHide)
        todayRecyclerView.adapter = adapter
    }
}